package com.itheima.reggie.controller;

import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.User;
import com.itheima.reggie.service.UserService;
import com.itheima.reggie.utils.SMSUtils;
import com.itheima.reggie.utils.ValidateCodeUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private RedisTemplate redisTemplate;


    /**
     * 作用： 发送短信
     *
     * @param user
     * @return
     */
    @RequestMapping("/sendMsg")
    public R<String> sendMsg(@RequestBody User user) {
        //1. 获取手机号
        String phone = user.getPhone();

        //2. 生成四位验证码
        String code = ValidateCodeUtils.generateValidateCode(4).toString();

        //3. 调用阿里的工具类去发送短信(备注： 每位同学发两次就要注释了)
        //SMSUtils.sendMessage("黑马旅游网","SMS_205126318",phone,code);
        log.info("=======本次验证码：=========" + code);
        //4. 把验证码存储到redis中,有效时间设置为5分钟。
        redisTemplate.opsForValue().set(phone, code,30, TimeUnit.SECONDS); //不好控制有效时间

        //5. 返回信息
        return R.success("发送成功");
    }


    /**
     * 作用： 登陆校验
     *
     * @param param 存储phone与用户输入的code
     * @return
     */
    @RequestMapping("/login")
    public R<User> login(@RequestBody Map<String, String> param, HttpSession session) {
        //1. 取出参数
        String phone = param.get("phone");
        String code = param.get("code"); //用户输入的验证码
        String codeInSession = (String) redisTemplate.opsForValue().get(phone);
        //2. 把参数交给Service,返回当前登陆者对象
        User user = userService.login(phone, code, codeInSession);
        //登录成功要做一个登录成功标记
        if (user != null) {
            //登入成功清除验证码
            redisTemplate.opsForValue().get(phone);
            session.setAttribute("user", user.getId());
        } else {
            return R.error("登陆失败");
        }
        //3. 返回响应
        return R.success(user);
    }
    /*个人中心推出登入*/
    @PostMapping("/loginout")
    public R<String> loginOut(HttpSession session){
        session.invalidate();//退出登入,清除session
        return R.success("退出成功");
    }
}
